package com.imooc.security.browser.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.security.core.properties.LoginType;
import com.imooc.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author sherry
 * @Description
 * @Date Create in 2019-03-18
 * @Modified By:
 */
@Component("imoocAuthSuccessHandler")
@Slf4j
public class ImoocAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        log.info("登陆成功：{}", securityProperties.getBrowser().getLoginType());

        if (LoginType.JSON == securityProperties.getBrowser().getLoginType()) {//如果当前系统配置的是json请求
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//            response.getWriter().write(objectMapper.writeValueAsString(authentication));
            log.info(ReflectionToStringBuilder.toString(authentication, ToStringStyle.MULTI_LINE_STYLE));
            //然后按照默认处理，继续调用请求的接口
            super.onAuthenticationSuccess(request, response, authentication);
        } else {//如果当前系统配置的不是json，则按照默认处理
            //            redirectStrategy.sendRedirect(request,response,"/index1.html");//跳转到自定义的页面上
            super.onAuthenticationSuccess(request, response, authentication);
        }


    }
}
